package com.yuyou.fn.settlement.service.impl;

import com.github.wens.mybatisplus.examples.Example;
import com.github.wens.mybatisplus.plugins.Page;
import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.common.util.CriteriaUtils;
import com.yuyou.fn.common.util.TimeUtils;
import com.yuyou.fn.settlement.entity.MainAccount;
import com.yuyou.fn.settlement.service.IMainAccountService;
import com.yuyou.fn.settlement.vo.WithdrawalQueryVo;
import org.springframework.stereotype.Service;

import com.yuyou.fn.settlement.mapper.WithdrawalMapper;
import com.yuyou.fn.settlement.entity.Withdrawal;
import com.yuyou.fn.settlement.service.IWithdrawalService;
import com.github.wens.framework.service.impl.SuperServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 *
 * Withdrawal 表数据服务层接口实现类
 *
 */
@Service
public class WithdrawalServiceImpl extends SuperServiceImpl<WithdrawalMapper, Withdrawal,Long> implements IWithdrawalService {


    @Resource
    private IMainAccountService mainAccountService ;

    @Override
    public Page<Withdrawal> findWithdrawalByQuery(WithdrawalQueryVo withdrawalQueryVo, int pageNo, int pageSize) {
        Example<Withdrawal> example = Withdrawal.createExample();
        example.orderBy("createTime").desc();
        Example.Criteria criteria = example.createCriteria();
        CriteriaUtils.fillCondition(criteria,withdrawalQueryVo);
        return findPageByExample(example,pageNo,pageSize );
    }

    @Transactional
    @Override
    public void applyWithdrawal(Long mainAccountId, BigDecimal amount, String bankName, String bankCity, String cardUser, String cardNo) {
        MainAccount mainAccount = mainAccountService.findById(mainAccountId);
        if(mainAccount.getBalanceAmount().compareTo(amount) < 0 ){
            throw new BusException("提现金额超出余额");
        }
        Withdrawal withdrawal = new Withdrawal();
        withdrawal.setAmount(amount);

        withdrawal.setAreaTeamId(mainAccount.getAreaTeamId());
        withdrawal.setBusTeamId(mainAccount.getBusTeamId());
        withdrawal.setMainAccountId(mainAccount.getMainAccountId());
        withdrawal.setMainAccountName(mainAccount.getName());
        withdrawal.setBankCity(bankCity);
        withdrawal.setBankName(bankName);
        withdrawal.setCardNo(cardNo);
        withdrawal.setCardUser(cardUser);
        withdrawal.setUpdateTime(TimeUtils.now());
        withdrawal.setCreateTime(TimeUtils.now());
        withdrawal.setStatus(0);
        insertSelective(withdrawal);
        mainAccountService.increaseBalance(mainAccountId,amount.multiply(new BigDecimal(-1)));
    }

    @Override
    public void updateWithdrawalStatus(Long withdrawalId, Integer status) {
        Withdrawal update = new Withdrawal();
        update.setWithdrawalId(withdrawalId);
        update.setStatus(status);
        updateSelectiveById(update);
    }
}